﻿using AutoMapper;
using Canteen.Core.Models;
using Canteen.Core.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

namespace Canteen.Core.WebApp.API.Controllers
{
    [Route("user")]
    [ApiController, Authorize(Roles = "webapp")]
    public class UserController : ControllerBase
    {
        #region 构造函数
        private readonly IMapper mapper;
        private readonly IUserService userService;
        public UserController(IMapper mapper,IUserService userService)
        {
            this.mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
            this.userService = userService ?? throw new ArgumentNullException(nameof(userService));
        }
        #endregion

        #region 登录注册
        // POST /user/login
        [HttpPost("login"), AllowAnonymous]
        public async Task<HttpResult<object>> PostLogin([FromBody] UserLoginViewModel obj)
        {
            User user = await userService.UserLogin(obj.Phone, obj.PassWord);
            UserViewModel login = new UserViewModel()
            {
                Id = user.Id,
                Code = user.Code,
                Name = user.Name,
                Phone = user.Phone
            };
            var jwtAuthResult = await userService.SetUserLogin(user);
            if (jwtAuthResult is null) throw new Exception("设置登录失败");
            //6、返回结果
            return Result.Success(new
            {
                jwtAuthResult.AccessToken,
                jwtAuthResult.RefreshToken,
                user = login
            });
        }
        // POST /user/register
        [HttpPost("register"), AllowAnonymous]
        public async Task<HttpResult<bool>> PostRegister([FromBody] User obj)
        {
            await userService.CreateUser(obj);
            return HttpResult<bool>.Success(true);
        }
        #endregion

        #region 获取用户信息
        // GET: /user
        [HttpGet]
        public async Task<HttpResult<UserDTO>> Get()
        {
            var user = await userService.SelectUser();
            return HttpResult<UserDTO>.Success(mapper.Map<UserDTO>(user));
        }
        #endregion

        // GET: /user/recharge/pagelist
        [HttpGet("Recharge/PageList")]
        public async Task<HttpResult<dynamic>> GetRechargePageList([FromQuery] ShopOrderPageParameters parameters)
        {
            parameters.UserId = userService.UserId;
            return HttpResult<dynamic>.Success(await userService.GetRechargePageList(parameters));
        }
    }
}
